package com.qumitech.visualnovel.controller.rest;

import com.qumitech.visualnovel.model.common.BaseRsp;
import com.qumitech.visualnovel.model.common.ResultEnum;
import com.qumitech.visualnovel.model.dao.console.UserInfo;
import com.qumitech.visualnovel.pubdef.dto.push.PushMessageAdminDTO;
import com.qumitech.visualnovel.pubdef.dto.push.query.PushMessageQueryAdminDTO;
import com.qumitech.visualnovel.service.account.AccountGroupService;
import com.qumitech.visualnovel.service.push.PushMessageService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/push_message")
public class PushMessageController {

    @Autowired
    private PushMessageService pushMessageService;

    @Autowired
    private AccountGroupService groupService;

    @Autowired
    private void setPushMessageService(PushMessageService pushMessageService){
        this.pushMessageService = pushMessageService;
    }

    @PostMapping("/cfg")
    public BaseRsp saveCfg(@RequestBody PushMessageAdminDTO adminDTO){
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        adminDTO.setOperator(activeUser.getUsername());
        byte receiveType = 3;
        if (adminDTO.getReceiveType() == receiveType) {
            adminDTO.setReceiveType((byte) 1);
            List<String> userGroupIds = groupService.getGroups(adminDTO.getReceiveGroup(), 200);
            // 分批发送处理
            for (String uids: userGroupIds) {
                adminDTO.setReceiveValue(uids);
                pushMessageService.saveMessagePushConfig(adminDTO);
            }
        } else {
            pushMessageService.saveMessagePushConfig(adminDTO);
        }
        return new BaseRsp(ResultEnum.SUCCESS);
    }

    @GetMapping("/cfg")
    public BaseRsp listCfg(PushMessageQueryAdminDTO queryDTO){
        return pushMessageService.listMessagePushConfig(queryDTO);
    }

    @PutMapping("/cfg/{message_id}")
    public BaseRsp updateCfg(@PathVariable("message_id") String messageId, @RequestBody PushMessageAdminDTO adminDTO){
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        adminDTO.setOperator(activeUser.getUsername());
        return pushMessageService.updateMessagePushConfig(messageId, adminDTO);
    }

    @DeleteMapping("/cfg/{message_id}")
    public BaseRsp rmCfg(@PathVariable("message_id") String messageId){
        return pushMessageService.rmMessagePushConfig(messageId);
    }

}
